<template>
  <div class="gothrough">
    <!-- 面包屑 -->
    <Headline :headline1="$t('m.AccessAdmin')+'  /  '" :headline2="$t('m.PassageOfTime')"></Headline>
    <a-card style="width: 100%">
      <div class="lass-flex">
        <a-tree-select
          v-model="value"
          show-search
          style="width: 30%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder="Please select"
          allow-clear
          @change="gochecked"
          tree-default-expand-all
        >
      
          <a-tree-select-node
            v-for="item in items"
            :key="item.id"
            :cont="item"
            :value="item.areaname"
            :title="item.areaname"
          >
            <a-tree-select-node
              v-for="int in item.children"
              :key="int.id"
              :cont="int"
              :value="int.areaname"
              :title="int.areaname"
            >
              <a-tree-select-node
                v-for="ins in int.children"
                :key="ins.id"
                :cont="ins"
                :value="ins.areaname"
                :title="ins.areaname"
              />
            </a-tree-select-node>
          </a-tree-select-node>
        </a-tree-select>
        <a-input-search
          :placeholder="$t('m.PleaseEnterYourSearchTerms')"
          style="width: 200px; margin-left: 15px"
          size="default"
          v-model="gothfrom.key"
          @search="gothSearch"
        />
        <div class="chend">
          <a-checkbox :defaultChecked="gothfrom.vChild" @change="textChange">
            {{$t('m.WhetherToDisplayChildNodes')}}
          </a-checkbox>
        </div>
        <div class="btn-dispos">
          <a-button
            class="btn-dispo"
            style="width: 100%; height: 32px"
            type="primary"
            @click="gothbtn"
            >{{$t('m.PeriodDownload')}}</a-button
          >
        </div>
        <div class="btn-dispos">
          <a-button
            class="btn-dispo"
            style="width: 100%; height: 32px"
            type="primary"
            @click="addbtn"
            >{{$t('m.Thenewperiodoftime')}}</a-button
          >
        </div>
      </div>
      <a-table
        style="margin-top: 15px; overflow-x: auto"
        :rowKey="(r, i) => r.id"
        :columns="columns"
        :data-source="datas"
        bordered
        :pagination="false"
        :row-selection="{
          onChange: authSelectChange,
          type: 'checkbox',
          selectedRowKeys: setsclete,
        }"
      >
        <div slot="index" slot-scope="text, tag, i">
          {{ i + 1 }}
        </div>
        <div slot="tags" slot-scope="text, tags, i">
          <a-button
            class="btn"
            type="primary"
            icon="diff"
            @click="lookgoth(text, tags, i)"
            >{{$t('m.Examine')}}</a-button
          >
        </div>
      </a-table>
      <a-pagination
        class="pages"
        show-size-changer
        :defaultPageSize="10"
        :default-current="1"
        :total="total"
        @change="gothPages"
        :pageSizeOptions="['10', '15', '20']"
        @showSizeChange="gothChange"
      />
    </a-card>
    <Delete ref="delete" :dalete="dalete" @confirm="gothdelete"></Delete>
    <Delete ref="deletes" :dalete="deletes" @confirm="mendelete"></Delete>
    <!-- 新增权限组 -->
    <Modal :modal="gothfack" @modalLast="authOk" @modalhand="authhand">
      <div class="lass-flex">
        <div class="btn-dispos">
          <a-button
            class="btn-dispo"
            style="width: 100%; height: 32px"
            type="primary"
            @click="editbtn"
            >{{$t('m.ModifyTheTime')}}</a-button
          >
        </div>
        <div class="btn-dispos">
          <a-button
            class="btn-dispo"
            style="width: 100%; height: 32px"
            type="primary"
            @click="detelebtn"
            >{{$t('m.DeleteTheTime')}}</a-button
          >
        </div>
      </div>
      <a-table
        style="margin-top: 15px; overflow-x: auto"
        :rowKey="(r, i) => r.id"
        :columns="column"
        :data-source="datatimes"
        bordered
        :pagination="false"
        :row-selection="{
          onChange: gothSelectChange,
          type: 'checkbox',
          selectedRowKeys: gothsetsclete,
        }"
      >
        <div slot="index" slot-scope="text, tag, i">
          {{ i + 1 }}
        </div>
        <div slot="tags" slot-scope="text, tags, i">
          <a-button
            class="btn"
            type="primary"
            icon="diff"
            @click="lookgoth(text, tags, i)"
            >{{$t('m.Examine')}}</a-button
          >
        </div>
      </a-table>
    </Modal>
    <!-- 新增时段 -->
    <Modal :modal="addfack" @modalLast="addtimeOk" @modalhand="addtimehand">
      <div class="onlode">
        <a-form-item class="logflex" :label="$t('m.Start')" validate-status="success">
          <a-time-picker
            :valueFormat="addtimes.startTime"
            :default-value="moment('00:00', 'HH:mm')"
            format="HH:mm"
            @change="ondateChange"
          />
        </a-form-item>
        <a-form-item class="logflex" :label="$t('m.End')" validate-status="success">
          <a-time-picker
            :valueFormat="addtimes.endTime"
            :default-value="moment('23:59', 'HH:mm')"
            format="HH:mm"
            @change="endateChange"
          />
        </a-form-item>
      </div>
      <div class="onlode">
        <a-form-item
          style="display: flex; align-items: center"
          :label="$t('m.DateSelection')"
        >
          <a-checkbox-group  @change="onChange">
            <a-row>
              <a-col :span="3">
                <a-checkbox value="0"> {{$t('m.Sunday')}} </a-checkbox>
              </a-col>
              <a-col :span="3">
                <a-checkbox value="1"> {{$t('m.Monday')}} </a-checkbox>
              </a-col>
              <a-col :span="3">
                <a-checkbox value="2"> {{$t('m.Tuesday')}} </a-checkbox>
              </a-col>
              <a-col :span="3">
                <a-checkbox value="3"> {{$t('m.Wednesday')}} </a-checkbox>
              </a-col>
              <a-col :span="3">
                <a-checkbox value="4"> {{$t('m.Thursday')}} </a-checkbox>
              </a-col>
              <a-col :span="3">
                <a-checkbox value="5"> {{$t('m.Friday')}} </a-checkbox>
              </a-col>
              <a-col :span="3">
                <a-checkbox value="6"> {{$t('m.Saturday')}} </a-checkbox>
              </a-col>
              <a-col :span="3">
                <a-checkbox value="7"> 假日 </a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </a-form-item>
      </div>
    <div class="onlode">
        <a-form-item class="logflex" :label="$t('m.periodofvalidity')" validate-status="success">
        <a-date-picker v-model="addtimes.endDate" @change="dateChange" />
      </a-form-item>
      <a-form-item class="logflex" :label="$t('m.OpenType')">
        <a-select
          v-model="addtimes.recognition"
          class="select-a"
          @change="openSelectChange"
        >
          <a-select-option
            v-for="item in types"
            :value="item.code"
            :key="item.code"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </div>
    </Modal>
  </div>
</template>

<script>
import Headline from "@/components/Headline";
import Modal from "@/components/common/Modal";
import Delete from "@/components/Delete";
import {
  getDevAreaTree,
  getimeDeviceList,
  getcDownload,
  getLokDeviceList,
  deleteTimeZone,
  saveTimeZone
} from "@/api/entrance/entranceguard";
import { getdiction } from "@/api/dictionaries";
import moment from "moment";
export default {
  name: "GoThroughs",
  components: {
    Headline,
    Modal,
    Delete,
  },
  data() {
    return {
      items: [],
      value: "",
      gothfrom: {
        areaCode: "",
        key: "",
        vChild: true,
        start: 0,
        page: 1,
        limit: 10,
      },
      columns: [
        {
          title: this.$t('m.deviceNumber'),
          dataIndex: "machineid",
        },
        {
          title: this.$t('m.Equipment'),
          dataIndex: "devname",
        },
        {
          title: this.$t('m.Relay'),
          dataIndex: "relays",
          customRender: function (text, record, index) {
            return text + 1 + "号继电器";
          },
        },
        {
          title: this.$t('m.AccessControlOrAccess'),
          dataIndex: "readheadname",
        },
        {
          title: this.$t('m.Operation'),
          key: "tags",
          // dataIndex: "address",
          scopedSlots: { customRender: "tags" },
        },
      ],
      column: [
        {
          title:  this.$t('m.DownloadStatus'),
          dataIndex: "statusname",
        },
        {
          title: this.$t('m.Start'),
          dataIndex: "starttime",
        },
        {
          title: this.$t('m.End'),
          dataIndex: "endtime",
        },
        {
          title: this.$t('m.openDay'),
          dataIndex: "weekvalue",
          customRender: function (text, record, index) {
            let num = ["周日", "一", "二", "三", "四", "五", "六", "假日"];
            let arr = text.split(",");
            var slet = "";
            arr.forEach((el, index) => {
              if (el == 1) {
                if (index == num.length - 1) {
                  slet += num[index];
                } else {
                  slet += num[index] + "、";
                }
              }
            });
            return slet;
          },
        },
        {
          title: this.$t('m.OpenType'),
          dataIndex: "recognitionname",
        },
        {
          title: this.$t('m.ValidDate'),
          dataIndex: "enddate",
        },
        {
          title: this.$t('m.ProcessingTimes'),
          dataIndex: "downnum",
        },
        {
          title: this.$t('m.creationTime'),
          dataIndex: "createdate",
        },
      ],
      datas: [],
      setsclete: [],
      total: 0,
      doorIds: "",
      dalete: {
        titles: this.$t('m.DownloadPrompt'),
        type: "exclamation-point",
        text: this.$t('m.AreYouSureToReDownload'),
      },
      daletes: {
        titles: this.$t('m.DeleteThePrompt'),
        type: "exclamation-point",
        text: this.$t('m.AreYouSureToDeleteThisData'),
      },
      deletes: {
        titles: this.$t('m.DeleteThePrompt'),
        type: "exclamation-point",
        text: this.$t('m.AreYouSureToDeleteThisData'),
      },
      gothfack: {
        visible: false,
        width: "1000px",
        title: this.$t('m.AddPermissionGroup'),
      },
      addfack: {
        visible: false,
        width: "700px",
        title: this.$t('m.Thenewperiodoftime'),
      },
      doorId: "",
      datatimes: [],
      gothsetsclete: [],
      deletemen: {
        ids: "",
        doorId: "",
      },
      addtimes: {
        id: 0,
        weekValue: "",
        downStatus: 0,
        devData: [],
        startTime: "00:00",
        endTime: "23:59",
        endDate: "2050-01-20",
        recognition: "1",
      },
      dictionfrom: {
        groupcode: "SYS0000037",
        insertall: "",
        where: "",
        page: 1,
        start: 0,
        limit: 25,
      },
      types: [],
      chends:['0','1','2','3','4','5','6','7','8']
    };
  },
  created() {
    this._getDevAreaTree();
    this._getdiction();
  },
  methods: {
    moment,
    //获取字典
    _getdiction() {
      getdiction({ params: this.dictionfrom }).then((res) => {
        console.log(res);
        this.types = res.data.data;
      });
    },

    //获取区域数据
    _getDevAreaTree() {
      getDevAreaTree({ params: { key: "" } }).then((res) => {
        console.log(res);
        this.items = res.data;
         this._chexd();
      });
    },
    _getimeDeviceList() {
      getimeDeviceList({ params: this.gothfrom }).then((res) => {
        console.log(res);
        this.datas = res.data.data;
        this.total = res.data.total;
      });
    },
    //树形选中
    gochecked(value, label, extra) {
      if (extra.triggerNode) {
        //获取当前选中的对象信息
        const cont = extra.triggerNode.$attrs.cont;
        console.log(cont);
        this.gothfrom.areaCode = cont.areacode;
        this._getimeDeviceList();
      }
    },
    //搜索
    gothSearch() {
      this._getimeDeviceList();
    },
    //子节点
    textChange() {
      this.gothfrom.vChild = !this.gothfrom.vChild;
      this._getimeDeviceList();
    },
    gothbtn() {
      if (this.setsclete.length !== 0) {
        this.$refs.delete.visible = true;
      } else {
        this.$message.error("请选择数据");
      }
    },
        // 默认展示数据
    _chexd() {
      //默认选择第一条数据
      const item = this.items[0];
      console.log(item);
      this.gothfrom.areaCode = item.areacode;
      // this.contfromlist.areaCode = item.areacode;
      // this.formlists.status = item.status;
      this.value = item.areaname;
      this._getimeDeviceList();
    },
    //下载确定
    gothdelete() {
      getcDownload({ doorIds: this.doorIds })
        .then((res) => {
          const msg = res.data.msg;
          if (res.data.success) {
            this.$message.success(msg);
            this._getimeDeviceList();
            this.setsclete = [];
          } else {
            this.$message.srror(msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      this.$refs.delete.visible = false;
    },
    //新增时段
    addbtn() {
      if (this.setsclete.length > 0) {
        this.addfack.visible = true;
      } else {
        this.$message.error("请选择控制器");
      }
    },
    addtimeOk() {
      this.addtimes.devData =JSON.stringify(this.addtimes.devData)
      saveTimeZone(this.addtimes).then(res=>{
        const msg = res.data.msg
        if(res.data.success){
          this.$message.success(msg)
           this._getLokDeviceList();
        }else {
          this.$message.error(msg)
        }
      }).catch(err=>{
        console.log(err)
      })
       this.addtimes.weekValue=""
        this.addtimes.id = 0
        this.gothsetsclete= []
       this.addfack.visible = false;
    },
    addtimehand() {
        this.addfack.visible = false;
    },
    authSelectChange(select, text) {
      console.log(select, text);
      this.addtimes.devData = [];
      const texts = text;
      texts.forEach((item) => {
        console.log(item)
        let obj = {};
        obj.devId = item.devid;
        obj.relays = item.relays;
        obj.doorReadHeadId = item.id;
        this.addtimes.devData.push(obj);
      });
      this.setsclete = select;
      this.doorIds = select.join(",");
    },
    // 查看
    lookgoth(text, tags, i) {
      this.gothfack.visible = true;
      console.log(tags);
      this.doorId = tags.id;
      this.deletemen.doorId = tags.id;
      this._getLokDeviceList();
    },
    _getLokDeviceList() {
      getLokDeviceList({
        params: { doorId: this.doorId, page: 1, start: 0, limit: 50 },
      }).then((res) => {
        console.log(res);
        this.datatimes = res.data;
      });
    },
    authOk() {},
    authhand() {
      this.gothsetsclete = [];
      this.deletemen.ids = "";
    },
    gothSelectChange(select, text) {
      this.gothsetsclete = select;
      console.log(text)
      this.addtimes.id = text[0].id
      this.deletemen.ids = select.join(",");
    },
    //删除时段
    detelebtn() {
      if (this.gothsetsclete.length > 0) {
        this.$refs.deletes.visible = true;
      } else {
        this.$message.error("请选择要删除的数据");
      }
    },
    mendelete() {
      deleteTimeZone(this.deletemen)
        .then((res) => {
          const msg = res.data.msg;
          if (res.data.success) {
            this.$message.success(msg);
            this._getLokDeviceList();
            this.gothsetsclete = [];
            this.deletemen.ids = "";
          } else {
            this.$message.error(msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
      
      this.$refs.deletes.visible = false;
    },
    //修改时段
    editbtn() {
       if (this.gothsetsclete.length == 0 ) return this.$message.error("请选择时段")
         if (this.gothsetsclete.length > 1 ) {
          this.$message.error("只能选择一条时段");
      } else {
         this.addfack.visible = true;
      }
    },
    onChange(checkedValues) {
      const arr = ["0", "1", "2", "3", "4", "5", "6", "7"];
      console.log("checked = ", checkedValues);
      this.chends = checkedValues
      let arr1 = checkedValues.sort();
      arr.forEach((item, index) => {
        if (item == arr1[index]) {
          arr1[index] = 1;
        } else {
          arr1.splice(index, 0, 0);
        }
      });
      this.addtimes.weekValue = arr1.join(",");
    },
    openSelectChange() {},
    //时间处理
    ondateChange(date, dateString) {
      console.log(date, dateString);
      this.addtimes.startTime = dateString;
    },
    endateChange(date, dateString) {
      this.addtimes.endTime = dateString;
    },
    dateChange(date, dateString) {
      this.addtimes.endDate = dateString;
    },
    //分页
    gothPages(page, limit) {
      this.gothfrom.page = page;
      this.gothfrom.limit = limit;
      this.gothfrom.start = (page - 1) * limit;
      this._getimeDeviceList();
    },
    gothChange(page, pageSize) {
      this.gothfrom.page = page;
      this.gothfrom.limit = pageSize;
      this.gothfrom.start = (page - 1) * pageSize;
      this._getimeDeviceList();
    },
  },
};
</script>

<style scoped lang="scss">
.lass-flex {
  display: flex;
  align-items: center;
}
.btn-dispos {
  margin-left: 15px;
}
.chend {
  margin-left: 15px;
}
.onlode {
  display: flex;
  justify-content: center;
}
.logflex {
  display: flex;
  width: 50%;
  justify-content: center;
}
</style>